﻿using System.Linq;
using BLL.Models.Administrators;
using BLL.Security;

namespace BLL.Services.Administrators
{
    /// <summary>
    /// Service for administrator
    /// </summary>
    public class AdministratorsService: IAdministratorsService
    {
        private readonly AdministratorsCollection _administratorsCollection;

        /// <summary>
        /// Initializes a new instance of the <see cref="AdministratorsService" /> class.
        /// </summary>
        /// <param name="administratorsCollection">The administrators collection.</param>
        public AdministratorsService(AdministratorsCollection administratorsCollection)
        {
            _administratorsCollection = administratorsCollection;
        }

        /// <summary>
        /// Authenticates the specified login.
        /// </summary>
        /// <param name="login">The login.</param>
        /// <param name="password">The password.</param>
        public AuthenticationStatus Authenticate(string login, string password)
        {
            var administrator = GetAdministrator(login);
            if (administrator == null)
                return AuthenticationStatus.NotFound;
            if (!string.IsNullOrEmpty(password))
            {
                // We use registration date as a salt in order to avoid extra field and increase secutiry
                byte[] salt = administrator.Salt;
                byte[] encryptedPassword = Cryptographer.GenerateHash(password, salt);

                if (!encryptedPassword.SequenceEqual(administrator.Password))
                {
                    return AuthenticationStatus.PaswordInvalid;
                }
            }
            return AuthenticationStatus.Success;
        }

        /// <summary>
        /// Gets the administrator.
        /// </summary>
        /// <param name="login">The login.</param>
        public Administrator GetAdministrator(string login)
        {
            return _administratorsCollection.GetByLogin(login);
        }
    }
}